<template>
  <div v-if="i18n" style="height: 100%">
    <drawer-layout>
      <template v-slot:left="{ setFolded }">
        <fks-query-page
          v-loading="loading"
          :current-page.sync="currentPage"
          :page-size.sync="pageSize"
          :page-sizes="[20, 50, 100]"
          :total="total"
          :data="moduleData"
          :table-name="LANG.TABLENAME"
          layout="total,sizes,prev,pager,next,jumper"
          @sort-change="sortHandler"
          @query="getModules"
        >
          <template slot="singleSearch">
            <div class="single-searchBox">
              <fks-input
                v-model="keywords"
                size
                maxlength="50"
                class="single-searchBox-item"
                clearable
                :placeholder="LANG.NAME_OR_CODE"
                @keyup.native.enter="search"
                @clear="search"
              >
                <fks-button
                  slot="append"
                  icon="fks-icon-search"
                  @click="search"
                />
              </fks-input>
              <fks-button
                v-permission="['i18n:lang:select']"
                @click="openLang()"
              >
                <i class="fks-icon-earth" />
                {{ LANG.LANG_CHOOSE }}
              </fks-button>
              <fks-button
                v-permission="['i18n:add']"
                type="primary"
                icon="fks-icon-plus"
                @click="openAddModule"
              >
                {{ LANG.ADD }}
              </fks-button>
            </div>
          </template>
          <template>
            <fks-table-column
              type="index"
              label="#"
              width="60"
              align="center"
            />

            <fks-table-column
              sortable="custom"
              prop="code"
              :label="LANG.CODE"
              align="left"
              header-align="center"
              is-link
              min-width="100"
            >
              <span
                slot-scope="scope"
                @click="
                  () => {
                    getLangDetail(scope)
                    setFolded(true)
                  }
                "
              >
                {{ scope.row.code }}
              </span>
            </fks-table-column>
            <fks-table-column
              prop="name"
              :label="LANG.NAME"
              align="left"
              header-align="center"
            />
            <fks-table-column :label="LANG.OPERATION" width="100" align="left">
              <span slot-scope="scope">
                <fks-button
                  v-permission="['i18n:edit']"
                  type="text"
                  @click="editModule(scope.row, scope.$index)"
                  >{{ LANG.EDIT }}</fks-button
                >
                <fks-button
                  v-permission="['i18n:delete']"
                  danger-text
                  @click="delModule(scope.row, false)"
                  >{{ LANG.DELETE }}</fks-button
                >
              </span>
            </fks-table-column>
          </template>
        </fks-query-page>
      </template>
      <template #right>
        <lang-edit
          :id="rowId"
          :table-name="rightTitle"
          :table-code="rightCode"
          @submit="finishLangConfig"
        />
      </template>
    </drawer-layout>

    <module-detail
      :visible="add_module"
      :type="type"
      :data="current_module"
      @close="closeAddModule"
      @submit="finishAddModule"
    />
    <fks-dialog
      :append-to-body="true"
      :visible.sync="langVisible"
      width="960px"
      destroy-on-close
      @close="closeLang"
      @open="openLang"
    >
      <div slot="title">
        <i class="fks-icon-earth" style="margin-right: 0" />
        {{ LANG.LANG_CHOOSE }}
      </div>
      <div
        v-for="(item, index) in langData"
        :key="index"
        class="language-select"
      >
        <div class="language-select-item">
          <fks-checkbox-group v-model="langChecked">
            <fks-checkbox :key="item.code" :label="item.code">
              {{ item.name }}
            </fks-checkbox>
          </fks-checkbox-group>
        </div>
      </div>
      <div slot="footer">
        <fks-button type="primary" icon="fks-icon-check" @click="saveLang()">
          {{ LANG.SAVE }}
        </fks-button>
      </div>
    </fks-dialog>
  </div>
  <unavailable-tip v-else />
</template>

<script>
import { SET_ENUM } from '@/store/Mutation/mutationTypes'
import Mix from '@/mixins/module'
import UnavailableTip from './components/Unavailable'
import LangEdit from './components/LangEdit'
import DrawerLayout from '@/components/DrawerLayout'
import { SET_CLIENT_CONFIG } from '@/store/Mutation/mutationTypes'
import { lang } from './langClass'
import {
  getModules,
  getResource,
  deleteModule,
  saveResource,
  save,
  editCurrentModule,
  getAllDetail,
  searchModule
} from './api/common'
import {
  PUT_CLIENT_CONFIG,
  GET_LATEST_CLIENT_CONFIG
} from '@/store/Action/actionTypes'
import ModuleDetail from './components/ModuleDetail'
import { ENUM, LATEST_CLIENT_CONFIG } from '@/store/State/stateTypes'
// import { mapMutations } from 'vuex'
// import { SET_LOCAL_LANG } from '@/store/Mutation/mutationTypes'
import * as types from '@/store/Getter/getterTypes.js'
export default {
  name: 'Lang',
  components: { LangEdit, ModuleDetail, UnavailableTip, DrawerLayout },
  mixins: [Mix],
  data() {
    return {
      loading: true,
      firstAccess: true,
      rightTitle: '',
      rightCode: '',
      moduleData: [],
      current_row: {}, //当前资源
      current_roww: {}, //当前资源
      current_cate: {}, //当前类别
      add_module: false,
      rowIndex: '',
      type: '',
      currentPage: 1,
      pageSize: 20,
      total: 0,
      keywords: '',
      rowId: 0,
      sort: '',
      sortValue: '',
      langData: lang,
      langVisible: false,
      langChecked: [],
      langList: []
    }
  },
  computed: {
    theme() {
      return this.$store.getters[types.THEME]
    },
    languages() {
      return this.$store.state[ENUM].languages || []
    },
    isCate() {
      return this.type == '0'
    },
    current_module() {
      if (this.isCate) {
        return this.current_cate
      } else {
        return this.current_row
      }
    },
    i18n() {
      return this.$store.getters[types.I18N]
    },
    latestClientConfig() {
      return this.$store.state[LATEST_CLIENT_CONFIG]
    }
  },
  watch: {
    latestClientConfig(nval) {
      this.langList = nval.additionalInformation.langConfig
      this.langChecked = this.langList.map((item) => {
        return item.code
      })
    }
  },
  mounted() {
    this.getModules()
    this.$store.dispatch(GET_LATEST_CLIENT_CONFIG)
  },
  methods: {
    // ...mapMutations({
    //   SET_LOCAL_LANG: SET_LOCAL_LANG
    // }),
    sortHandler(data) {
      let params = {}
      if (!data.order) {
        this.sort = ''
        this.sortValue = ''
      } else {
        this.sort = data.order == 'ascending' ? 'asc' : 'desc'
        this.sortValue = data.prop == 'code' ? 'code' : 'update_date '
      }
      params = {
        name: this.keywords,
        page: this.currentPage,
        size: this.pageSize,
        sort: this.sort,
        sortValue: this.sortValue
      }
      this.getModuleList(params)
    },
    /**
     * @description: 查询模块
     * @param {type}
     * @return:
     */
    getModules() {
      let params = {
        name: this.keywords,
        page: this.currentPage,
        size: this.pageSize,
        sort: this.sort,
        sortValue: this.sortValue
      }
      this.getModuleList(params)
    },
    getModuleList(params) {
      getModules(params)
        .then((res) => {
          if (res.status) {
            this.moduleData = [...res.data.list]
            this.total = res.data.total
            if (this.firstAccess) {
              this.editLang(this.moduleData[0], 0)
            }
          } else {
            this.moduleData = []
            this.total = 0
          }
          this.loading = false
        })
        .catch((error) => {
          this.moduleData = []
          this.total = 0
          this.loading = false
        })
    },
    search() {
      this.currentPage = 1
      let params = {
        name: this.keywords,
        page: 1,
        size: this.pageSize,
        sort: this.sort,
        sortValue: this.sortValue
      }
      searchModule(params)
        .then((res) => {
          if (res.status) {
            this.moduleData = [...res.data.list]
            this.total = res.data.total
          } else {
            this.moduleData = []
            this.total = 0
          }
        })
        .catch((error) => {
          this.moduleData = []
          this.total = 0
        })
    },
    /**
     * @description: 删除模块/类别
     * @param {type}
     * @return:
     */
    delModule(row, cate) {
      this.$confirm(this.LANG.DELETE_MODULE, {
        title: this.LANG.DELETE,
        confirmButtonText: this.LANG.DELETE,
        cancelButtonText: this.LANG.CANCEL,
        deleteMode: true
      })
        .then(() => {
          deleteModule(row.id)
            .then((res) => {
              if (res.status) {
                this.getModules()
                this.$message.success(this.LANG.DELETE_SUCCESS)
              }
            })
            .catch(() => {})
        })
        .catch(() => {})
    },
    /**
     * @description: 获取右边表格内容
     * @param {type}
     * @return:
     */
    editLang(row, index) {
      this.rightTitle = row.name
      this.rightCode = row.code
      this.rowId = row.id
      this.rowIndex = index
      this.firstAccess = false
    },
    getLangDetail(data) {
      this.rightTitle = data.row.name
      this.rightCode = data.row.code
      this.rowId = data.row.id
      this.rowIndex = data.$index
      this.firstAccess = false
    },
    /**
     * @description: 保存资源文件
     * @param {type}
     * @return:
     */
    finishLangConfig(configData) {
      saveResource(configData)
        .then((res) => {
          if (res.status) {
            this.$message.success(this.LANG.SAVE_SUCCESS)
          }
        })
        .catch(() => {})
    },
    /**
     * @description: 关闭类别/模块弹窗
     * @param {type}
     * @return:
     */
    closeAddModule() {
      this.add_module = false
    },
    /**
     * @description: 新增模块
     * @param {type}
     * @return:
     */
    openAddModule() {
      this.type = '1'
      this.current_row = Object.assign({
        edit: false,
        parentId: this.current_cate.id || 0
      })
      this.add_module = true
    },
    /**
     * @description: 编辑模块
     * @param {type}
     * @return:
     */
    editModule(row) {
      this.type = '2'
      this.current_row = Object.assign({ edit: true }, row)
      this.current_row.parentId = this.current_cate.id
      this.add_module = true
    },
    /**
     * @description: 保存类别/模块
     * @param {type}
     * @return:
     */
    finishAddModule(form) {
      let data = {
        code: form.code,
        name: form.name
      }
      if (this.type == '1') {
        //新增
        save(data)
          .then((res) => {
            if (res.status) {
              this.$message.success(this.LANG.ADD_SUCCESS)
              this.getModules()
              this.closeAddModule()
            }
          })
          .catch(() => {})
      }
      if (this.type == '2') {
        //编辑
        data.id = this.current_row.id
        editCurrentModule(data)
          .then((res) => {
            if (res.status) {
              this.$message.success(this.LANG.EDIT_SUCCESS)
              this.getModules()
              this.closeAddModule()
            }
          })
          .catch(() => {})
      }
    },
    /**
     * @description: 语种选择
     * @param {type}
     * @return:
     */
    openLang() {
      this.langVisible = true
    },
    closeLang() {
      this.langVisible = false
    },
    /**
     * @description: 存储已选中语言数据
     * @param: data
     * @return:
     */
    saveLang() {
      this.langList = []
      this.langChecked.forEach((item) => {
        this.langData.forEach((lang) => {
          if (item == lang.code) {
            this.langList.push(lang)
          }
        })
      })
      let additionalInfo = {
        ...this.latestClientConfig.additionalInformation,
        langConfig: this.langList
      }
      let settingsJSON = {
        ...this.latestClientConfig,
        additionalInformation: additionalInfo
      }
      this.$store
        .dispatch(PUT_CLIENT_CONFIG, settingsJSON)
        .then((res) => {
          this.loading = false
          if (res.status) {
            this.$message({
              type: 'success',
              message: this.LANG.UPDATE_SUCCESS
            })
            this.$store.commit(SET_ENUM, {
              languages: this.langList
            })
          }
        })
        .catch(() => {
          this.loading = false
        })
      this.closeLang()
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .single-searchBox-item {
  width: 40%;
}
::v-deep .fks-icon-check {
  margin-right: 4px;
}

.dic {
  min-width: 632px;
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
}

.tree-head {
  height: 40px;
  margin-top: 12px;
  line-height: 40px;

  .head-title {
    display: inline-block;
    margin-left: 8px !important;
    font-weight: 600;
    font-size: 18px;
    color: #0d3d8b;
  }

  .head-btn {
    float: right;
    margin-top: 6px;
    margin-right: 8px;
  }
}

.lang-config {
  display: flex;
  height: 100%;
}

.tree-container {
  box-sizing: border-box;
  width: 250px;
  height: calc(100% - 40px);
  padding: 0 10px;
  margin-top: 20px;
  margin-left: 24px;
  border-radius: 4px;
  background-color: #f7f8f8;
}

.treenode-more {
  position: absolute;
  right: 10px;
  display: none;
  line-height: 24px;

  .fks-dropdown {
    font-size: inherit;
    color: inherit;
  }
}

.fks-tree-node__content:hover .treenode-more,
.treenode-more:focus {
  display: inline-block;
}

.language-select {
  display: inline-block;
  padding: 24px 32px 0;
}

.language-select-item {
  display: inline-block;
  width: 170px;
  height: 50px;
  padding-left: 52px;
  font-size: 14px;
}
</style>
